
import * as THREE from 'three'

import {common} from "./shaders.js"

let data = await (await fetch('../../wind_field_flat/assets/ne_110m_coastline.geojson')).json();
const positions = [];
const geometry = new THREE.BufferGeometry();
const material = new THREE.LineBasicMaterial( { color: '#fff' } );
for (let i = 0; i < data.features.length; i++) {
  const line = data.features[i].geometry.coordinates;
  for (let j = 0; j < line.length; j++) {
    const x = (line[j][0] + 180) * 2 / 360;
    const y = (line[j][1] + 90) * 1 / 180;
    positions.push(x, y, 0)
    if (j && j < line.length - 1)
      positions.push(x, y, 0)
  }
}
geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
const contours = new THREE.LineSegments(geometry, material );

contours.material.onBeforeCompile = function(shader, renderer, object) {
  let patch = (vs, tok, tokfn) => shader[vs] = shader[vs].replace(tok, tokfn(tok))

  patch('vertexShader', '#include <common>', tok => `
${tok}
${common}
`);
  patch('vertexShader', '#include <begin_vertex>', tok => `
    
        vec3 transformed = position;
        transformed.x *= .5;
    
        transformed = toSphere(transformed);
    `);
  if(contours.userData.sharedUniforms)
    Object.assign(shader.uniforms,contours.userData.sharedUniforms);
}

//let sphere = new THREE.Mesh(new THREE.SphereGeometry(.95,64,32),
let sphere = new THREE.Mesh(new THREE.PlaneGeometry(1,1,64,32),
    new THREE.MeshBasicMaterial({
      dithering:true,
      color:'black',
      map:null,
      //roughness:.75,
      ///metalness:.01,
      transparent:true,opacity:.5}));


sphere.material.onBeforeCompile = function(shader, renderer, object) {
  let patch = (vs, tok, tokfn) => shader[vs] = shader[vs].replace(tok, tokfn(tok))

  patch('vertexShader', '#include <common>', tok => `
    ${tok}
    ${common}
    `);
  patch('vertexShader', '#include <begin_vertex>', tok => `
    
        vec3 transformed = vec3(uv,-0.02);
        //transformed.x *= .5;
    
        transformed = toSphere(transformed);
    `);
  if(contours.userData.sharedUniforms)
    Object.assign(shader.uniforms,contours.userData.sharedUniforms);
}
export {contours,sphere};
